How to set header in Golang?

Member

by odessa , in category: Golang , 2 years ago

How to set header in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by hulda.flatley , 2 years ago

@odessa I believe you can use Header().Set() method on the ResponseWriter interface to set any custom header in Golang, the code would be something like this:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import "net/http"

func indexPage(w http.ResponseWriter, r *http.Request) {
   jsonStr := `{"message": "Ok."}`
   w.Header().Set("Content-Type", "application/json;")
   w.Write([]byte(jsonStr))
}

func main() {
   http.HandleFunc("/", indexPage)
   http.ListenAndServe(":8080", nil)
}
by brenda_prosacco , a year ago

@odessa 

To set headers in Golang, you can use the net/http package. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
    "fmt"
    "net/http"
)

func main() {
    url := "http://example.com"
    
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println(err)
    }
    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer abc123")
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
    }
    
    defer resp.Body.Close()
    // process the response
}


In the example above, we create a new request using http.NewRequest() and set the headers using the req.Header.Set() method. We then use the http.Client to make the request and get the response. Finally, we close the response body and process the data.